package com.ruoyi.project.common;


import com.itextpdf.text.PageSize;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.io.OutputStream;
import java.net.URLEncoder;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;

import com.itextpdf.text.pdf.PdfWriter;

@Controller
public class TestController1 {
    @RequestMapping(value = "export", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity chartExport(HttpServletResponse response, String base64Info, HttpServletRequest request) throws IOException {
        String newFileName;
        newFileName = "统计图" + System.currentTimeMillis() + ".pdf";
        String newPngName = newFileName.replaceFirst(".pdf", ".png");
        String exportFilePath = "d:/test";
        base64Info = base64Info.replaceAll(" ", "+");
        BASE64Decoder decoder = new BASE64Decoder();
        String[] arr = base64Info.split("base64,");
        byte[] buffer;
        try {
            buffer = decoder.decodeBuffer(arr[1]);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        OutputStream output = null;
        try {
            output = new FileOutputStream(new File(exportFilePath + newPngName));//生成png文件
            output.write(buffer);
            output.flush();
            output.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Pdf(exportFilePath + newPngName, exportFilePath + newFileName);
        File f = new File(exportFilePath + newPngName);
        if (f.exists()) {
            f.delete();
        }

        try {
            byte[] fileBytes = FileUtils.readFileToByteArray(new File(exportFilePath + newFileName));
            HttpHeaders headers = new HttpHeaders();
            String fileName = newFileName;
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
            headers.setContentDispositionFormData("attachment", fileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setPragma("public");
            headers.setCacheControl("max-age=0");
            return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
        } catch (IOException e) {

            return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
        }

    }

    //经过png文件来生成pdf文件
    public File Pdf(String imagePath, String mOutputPdfFileName) {
        Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
        try {
            PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(mOutputPdfFileName));
            doc.open();
            doc.newPage();
            Image png1 = Image.getInstance(imagePath);
            float heigth = png1.getHeight();
            float width = png1.getWidth();
            int percent = this.getPercent2(heigth, width);
            png1.setAlignment(Image.MIDDLE);
            png1.setAlignment(Image.TEXTWRAP);
            png1.scalePercent(percent + 3);
            doc.add(png1);
            doc.close();
        }   catch (Exception e) {
            e.printStackTrace();
        }

        File mOutputPdfFile = new File(mOutputPdfFileName);
        if (!mOutputPdfFile.exists()) {
            mOutputPdfFile.deleteOnExit();
            return null;
        }
        return mOutputPdfFile;
    }

    private int getPercent2(float h, float w) {
        int p = 0;
        float p2 = 0.0f;
        p2 = 530 / w * 100;
        p = Math.round(p2);
        return p;
    }

    //输入流读取到输出流
    private void copy(BufferedInputStream input, BufferedOutputStream outputString) {
        byte[] but = new byte[1024];
        try {
            while (input.read() != -1) {
                int by = input.read(but);
                outputString.write(but, 0, by);
                outputString.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
